package com.sctek.smartglasses.ui;

import java.io.File;
import java.io.InputStream;
import java.util.Locale;
import java.io.FileOutputStream;
import java.util.Date;
import java.text.SimpleDateFormat;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
// import cn.ingenic.glasssync.ui.BindGlassActivity;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.ingenic.glasssync.DefaultSyncManager;
import cn.ingenic.glasssync.LocationReportService;
import cn.ingenic.glasssync.R;
import cn.ingenic.glasssync.SyncApp;
import cn.ingenic.glasssync.camera.PhotoModule;
import cn.ingenic.glasssync.contactslite.ContactsLiteModule;
import cn.ingenic.glasssync.devicemanager.GlassDetect;
import cn.ingenic.glasssync.devicemanager.WifiManagerApi;
import cn.ingenic.glasssync.camera.TakePictureModule;

import com.ingenic.glass.api.sync.SyncChannel.Packet;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.sctek.smartglasses.biz.BLContacts;
import com.sctek.smartglasses.db.ContactsDBHelper;
import com.sctek.smartglasses.fragments.SettingFragment;
import com.sctek.smartglasses.utils.HanLangCmdChannel;
import com.sctek.smartglasses.utils.HanLangNotifyChannel;
import com.sctek.smartglasses.utils.PhotosSyncRunnable;
import com.sctek.smartglasses.utils.VideoSyncRunnable;
import com.sctek.smartglasses.utils.WifiUtils;
import com.sctek.smartglasses.utils.WifiUtils.WifiCipherType;
import com.sctek.smartglasses.utils.RemoteMediaDownloader;

public class MainActivity extends BaseFragmentActivity {
	
	private  String TAG = "MainActivity";
	private final String DIRECTORY = Environment.getExternalStorageDirectory()
			.toString();
	private TextView photoTv;
	private TextView videoTv;
	private TextView settingTv;
	private TextView liveTv;
	private TextView unbindTv;
	private TextView aboutTv;
        private Button takePhotoBt;
        private Button takeVideoBt;
        private Button mSyncHotspotBt;
	private DefaultSyncManager mSyncManager;
	private HanLangCmdChannel mHanLangCmdChannel;
        protected SetWifiAPTask mWifiATask;
        protected WifiManager mWifiManager;
        public ProgressDialog mConnectProgressDialog;
        private boolean mRegistApStateBroadcastReceiver = false;
    private Context mContext;
    private static final int MESSAGE_UNBIND_START = 1;
    private static final int MESSAGE_UNBIND_FINISH = 2;
    public static final int MESSAGE_UPDATE_GLASS = 3;
    public static final int MSG_RESEDN_CONNECT_WIFI = 4;
    private GlassDetect mGlassDetect;
	private static MainActivity mInstance = null;
	public static MainActivity getInstance() {
		return mInstance;
	}
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.myactivity_main);
		getActionBar().hide();
		mInstance = this;
		SyncApp.getInstance().addActivity(this);
		photoTv = (TextView)findViewById(R.id.photo_tv);
		videoTv = (TextView)findViewById(R.id.video_tv);
		settingTv = (TextView)findViewById(R.id.setting_tv);
		liveTv = (TextView)findViewById(R.id.live_tv);
		unbindTv = (TextView)findViewById(R.id.unbind_tv);
		aboutTv = (TextView)findViewById(R.id.about_tv);
		takePhotoBt =(Button)findViewById(R.id.take_photo_bt);
		takeVideoBt =(Button)findViewById(R.id.take_video_bt);
		mSyncHotspotBt =(Button)findViewById(R.id.sync_phone_hotspot_bt);

		photoTv.setOnClickListener(mClickedListener);
		videoTv.setOnClickListener(mClickedListener);
		settingTv.setOnClickListener(mClickedListener);
		liveTv.setOnClickListener(mClickedListener);
		unbindTv.setOnClickListener(mClickedListener);
		aboutTv.setOnClickListener(mClickedListener);
		takePhotoBt.setOnClickListener(mClickedListener);
		takeVideoBt.setOnClickListener(mClickedListener);
		mSyncHotspotBt.setOnClickListener(mClickedListener);
		mSyncManager = DefaultSyncManager.getDefault();
		initImageLoader(getApplicationContext());		
		
		dialog = new ProgressDialog(MainActivity.this);
		
		mGlassDetect = (GlassDetect)GlassDetect.getInstance(getApplicationContext());
		mGlassDetect.setLockedAddress(mSyncManager.getLockedAddress());

		mHanLangCmdChannel = HanLangCmdChannel.getInstance(getApplicationContext());
		initSyncHotspot();

		SharedPreferences pref = getSharedPreferences(SyncApp.SHARED_FILE_NAME, Context.MODE_PRIVATE);
		
		boolean firstBind = getIntent().getBooleanExtra("first_bind", false);
		syncContactToGlass(false, firstBind);
		if(firstBind) {
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					startService(new Intent(MainActivity.this, LocationReportService.class));
				}
			}, 2000);
			mGlassDetect.set_audio_connect();
			mGlassDetect.set_a2dp_connect();
			Editor editor = pref.edit();
	    	editor.putBoolean("last_headset_state", true);
	    	editor.putBoolean("last_a2dp_state", true);
	    	editor.commit();
		}
		else if(pref.getBoolean("last_headset_state", false)&&
				(mGlassDetect.getCurrentHeadSetState() == BluetoothProfile.STATE_DISCONNECTED)) {
			mGlassDetect.set_audio_connect();
		}
		else if(pref.getBoolean("last_a2dp_state", false)&&
				(mGlassDetect.getCurrentA2dpState() == BluetoothProfile.STATE_DISCONNECTED)) {
			mGlassDetect.set_a2dp_connect();
		}
		
		//		TimeSyncManager.getInstance().syncTime();
		mHanLangCmdChannel.sendSyncTime();	
        TakePictureModule module = TakePictureModule.getInstance(this);
		module.registerHandler(handler);				
	}
    
        private void initSyncHotspot(){
	    mContext = this;
	    mHanLangCmdChannel.registerHandler("MainActivity",mCmdHandler);
	    mConnectProgressDialog = new ProgressDialog(mContext);
	    mConnectProgressDialog.setTitle(R.string.sync_phone_wifi_hotspot);
	    mConnectProgressDialog.setCancelable(false);
	    mConnectProgressDialog.setOnKeyListener(new OnKeyListener() { 
			
	    		@Override
	    		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
	    			if(keyCode == KeyEvent.KEYCODE_BACK) {
	    				dialog.cancel();
	    			}
	    			return false;
	    		}
	    	});
	    mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
	}
	private void syncContactToGlass(Boolean value, boolean firstBind){
		ContactsLiteModule clm = (ContactsLiteModule) ContactsLiteModule.getInstance(getApplicationContext());
		clm.sendSyncRequest(value,null);
		clm.setSyncEnable(value);
		BLContacts.getInstance(getApplicationContext()).syncContacts(false, firstBind);
	}
	
	private long currentTime = System.currentTimeMillis();
	@SuppressLint("NewApi")
	@Override
	public void onBackPressed() {
	// TODO Auto-generated method stub
		int stackCount = getFragmentManager().getBackStackEntryCount();
		if(stackCount != 0) {
			if(stackCount == 1)
			getFragmentManager().popBackStack();
		} else {
			
			long tempTime = System.currentTimeMillis();
			long interTime = tempTime - currentTime;
			if(interTime > 2000) {
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				currentTime = tempTime;
				return;
			}
			turnApOff();
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Locale local = getResources().getConfiguration().locale;
		RelativeLayout layout = (RelativeLayout)findViewById(R.id.main_background);
		InputStream is ;
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ARGB_8888;

		opt.inPurgeable = true;

		opt.inInputShareable = true;

		opt.inSampleSize = 1;

		if(local.getLanguage().contains("zh")) 
		    is= getResources().openRawResource(R.drawable.app_background_low);
		else 
		    is = getResources().openRawResource(R.drawable.app_background_en_low);
		Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
		BitmapDrawable bd = new BitmapDrawable(getResources(), bm);
		layout.setBackgroundDrawable(bd);
		PhotoModule.getInstance(getApplicationContext()).requestCameraState();
		HanLangNotifyChannel notifyChannel = HanLangNotifyChannel.getInstance(this);
		Packet getPower = notifyChannel.createPacket();
		getPower.putInt("type",HanLangNotifyChannel.MSG_TYPE_POWER_CHANGE);
		notifyChannel.sendPacket(getPower);
		getWifiConnectState();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you may tune some of them,
		// or you can create default configuration by
		//  ImageLoaderConfiguration.createDefault(this);
		// method.
		String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/.glasses_image_cache";
		File cacheFile = StorageUtils.getOwnCacheDirectory(context, cacheDir);
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.threadPoolSize(3)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024) // 50 Mb
				.diskCache(new UnlimitedDiskCache(cacheFile))
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.diskCacheExtraOptions(480, 320, null)
				.build();
		// Initialize ImageLoader with configuration.
		
		if(!ImageLoader.getInstance().isInited())
			ImageLoader.getInstance().init(config);
	}
	
	private OnClickListener mClickedListener = new OnClickListener() {
		
		@SuppressLint("NewApi")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
				case R.id.photo_tv:
					startActivity(new Intent(MainActivity.this, PhotoActivity.class));
					break;
				case R.id.video_tv:
					startActivity(new Intent(MainActivity.this, VideoActivity.class));
					break;
				case R.id.setting_tv:
					startActivity(new Intent(MainActivity.this, SettingActivity.class));
					break;
				case R.id.live_tv:
				    if (SyncApp.REMOTE_CAMERA_LIVE) {
					startActivity(new Intent(MainActivity.this,
								 SelectCameraLiveActivity.class));
				    } else {
					Intent intent = new Intent(MainActivity.this,
								       LiveDisplayActivity.class);
					startActivity(intent);
				    }
				    break;
				case R.id.unbind_tv:
					showUbindDialog();
					break;
				case R.id.about_tv:
					startActivity(new Intent(MainActivity.this, AboutActivity.class));
					break;
			        case R.id.take_photo_bt:
				    if(mHanLangCmdChannel.isConnected()) {//bluetooth is connected or not.
					    PhotoModule m = PhotoModule.getInstance(getApplicationContext());
					    m.send_take_photo();
					    takePhotoBt.setEnabled(false);
					    handler.postDelayed(takePhotoRunnable, 2000); 
				    }else{
					    Toast.makeText(MainActivity.this, R.string.bluetooth_error, Toast.LENGTH_LONG).show();
				    }
				    break;
				case R.id.take_video_bt:
				    if(mHanLangCmdChannel.isConnected()) {
					    PhotoModule.getInstance(getApplicationContext()).send_record();
					    takeVideoBt.setEnabled(false);
					    handler.postDelayed(takeVideoRunnable, 2000);
				    }else{
					    Toast.makeText(MainActivity.this, R.string.bluetooth_error, Toast.LENGTH_LONG).show();
				    }
				    break;
			        case R.id.sync_phone_hotspot_bt:
				     if(mHanLangCmdChannel.isConnected()) {
					     openApAndSendApInfoToGlass();
				     }else{
					     Toast.makeText(MainActivity.this, R.string.bluetooth_error, Toast.LENGTH_LONG).show();
				     }
				    break;
			default:
				break;
			}
		}
	};
	
	public void showUbindDialog() {
		
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(R.string.unbind);
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				try {
				GlassDetect glassDetect = (GlassDetect)GlassDetect.getInstance(getApplicationContext());
				glassDetect.set_audio_disconnect();
				glassDetect.set_a2dp_disconnect();

				disableLocalData();
				unBond();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		builder.create().show();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG,"onDestroy in");
		mInstance = null;
		handler.removeMessages(MSG_RESEDN_CONNECT_WIFI);
		SyncApp.getInstance().exitAllActivity();
		ImageLoader.getInstance().clearDiskCache();
		ImageLoader.getInstance().clearMemoryCache();
		ImageLoader.getInstance().destroy();
		mHanLangCmdChannel.unregisterHandler("MainActivity");
		if(mRegistApStateBroadcastReceiver)
		    mContext.unregisterReceiver(mApStateBroadcastReceiver);
	}
	
	ProgressDialog dialog;
	Handler handler = new Handler() {		
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case MESSAGE_UNBIND_START:
				dialog.setMessage(getResources().getText(R.string.unbonding));
				dialog.show();
				break;
			case MESSAGE_UNBIND_FINISH:
				if(dialog.isShowing())
					dialog.cancel();
				break;
			case TakePictureModule.MSG_RECEIVE_PICTURE_DATA_1:
			    byte [] picData1 = (byte[]) msg.obj;
			    addImage(picData1, 1);
			    Toast.makeText(MainActivity.this, "接受图片成功1", Toast.LENGTH_SHORT).show();
			    break;
			case TakePictureModule.MSG_RECEIVE_PICTURE_DATA_2:
			    byte [] picData2 = (byte[]) msg.obj;
			    addImage(picData2, 2);
			    Toast.makeText(MainActivity.this, "接受图片成功2", Toast.LENGTH_SHORT).show();
			    break;
			case MSG_RESEDN_CONNECT_WIFI:
			    sendApInfoToGlass();
			    break;
			}
		}
	};
	Handler mCmdHandler = new Handler() {
		String glassIp = "";
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case HanLangCmdChannel.CHECK_UPDATE_SUCCESS:
				showUpdateConfirmDialog();
				break;
			case HanLangCmdChannel.RECEIVE_MSG_FROM_GLASS:
			        Packet data = (Packet)msg.obj;
				int type = data.getInt("type");
				if(type == 15){
					glassIp = data.getString("ip");
					String connectSSid = data.getString("connected_ssid");
					Log.i(TAG,"---glassIp: "+glassIp+",connectSSid:"+connectSSid);
					if(glassIp != null && glassIp.length() != 0 && connectSSid != null && connectSSid.equals(WifiUtils.getValidSsid(mContext))){
					    handler.removeMessages(MSG_RESEDN_CONNECT_WIFI);
					    if(mConnectProgressDialog.isShowing())
						mConnectProgressDialog.dismiss();
					    mSyncHotspotBt.setTextColor(mContext.getResources().getColor(R.color.blue_text_color));
					    mSyncHotspotBt.setText(mContext.getResources().getString(R.string.sync_phone_wifi_hotspot_success));
					    if(SyncApp.SUPPORT_VISION) {
						    RemoteMediaDownloader mediaDownloader = RemoteMediaDownloader.getInstance(mContext);
						    mediaDownloader.startDownloadRemoteMedia(glassIp, "videos");
					    }
					    
					}else {
					    glassIp = "";
					    mSyncHotspotBt.setTextColor(mContext.getResources().getColor(R.color.black));
					    mSyncHotspotBt.setText(mContext.getResources().getString(R.string.sync_phone_wifi_hotspot));  
					}
				}else if(type == HanLangCmdChannel.GET_WIFI_CONNECT_STATE){
				    glassIp = data.getString("ip");
				    String glassSsid = data.getString("connected_ssid");
				    String phoneSsid = WifiUtils.getValidSsid(mContext);
				    Log.i(TAG,"glass connectssid:"+glassSsid+",phone ap ssid:"+phoneSsid);
				    if(glassIp != null && glassIp.length() != 0 && WifiUtils.getWifiAPState(mWifiManager) == WifiUtils.WIFI_AP_STATE_ENABLED && glassSsid != null && !glassSsid.equals("") && glassSsid.equals(phoneSsid)){
					    mSyncHotspotBt.setTextColor(mContext.getResources().getColor(R.color.blue_text_color));
					    mSyncHotspotBt.setText(mContext.getResources().getString(R.string.sync_phone_wifi_hotspot_success));
					    if(SyncApp.SUPPORT_VISION) {
						    RemoteMediaDownloader mediaDownloader = RemoteMediaDownloader.getInstance(mContext);
						    mediaDownloader.startDownloadRemoteMedia(glassIp, "videos");
					    }
					}else {
					    glassIp = "";
					    mSyncHotspotBt.setTextColor(mContext.getResources().getColor(R.color.black));
					    mSyncHotspotBt.setText(mContext.getResources().getString(R.string.sync_phone_wifi_hotspot));
					}
				}else if(type == HanLangCmdChannel.TYPE_GLASS_VIDEO_RECORD_STOPPED){
					Log.i(TAG,"glassIp = "+glassIp);
					if(SyncApp.SUPPORT_VISION) {
						if(glassIp != null && glassIp.length() != 0) {
							RemoteMediaDownloader mediaDownloader = RemoteMediaDownloader.getInstance(mContext);
							mediaDownloader.startDownloadRemoteMedia(glassIp, "videos");
						}else if(mHanLangCmdChannel.isConnected()) {
							openApAndSendApInfoToGlass();
						}
					}
				}
			    break;
			default:
			    break;
			}
		}
	};

        private void addImage(byte[] jpeg, int flag) {
		File dir = new File(DIRECTORY);
		if (!dir.exists())
			dir.mkdirs();
		String path = DIRECTORY + '/'
				+ generateName(System.currentTimeMillis()) + ".jpg";
		Log.i(TAG, "path  = " + path + "--jpeg.length = " + jpeg.length);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(path);
			out.write(jpeg);
		} catch (Exception e) {
			Log.e(TAG, "Failed to write image", e);
		} finally {
			try {
				out.close();
				Intent ti = new Intent();
				ti.setAction("cn.ingenic.kx.sendpic");
				ti.putExtra("kx.pic.path", path);
				ti.putExtra("kx.pic.flag", flag);
				getApplicationContext().sendBroadcast(ti);
			} catch (Exception e) {
			}

		}
	}

	private String generateName(long dateTaken) {
		Date date = new Date(dateTaken);
		SimpleDateFormat format = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss",
				Locale.US);
		String result = format.format(date);
		return result;
	}
	
	private void unBond() {
		new Thread(new Runnable() {
			@Override
			    public void run() {
				handler.sendEmptyMessage(MESSAGE_UNBIND_START);
				BLContacts.getInstance(getApplicationContext()).stopSyncContacts();
				ContactsDBHelper.getInstance(getApplicationContext(), null).clearAllData();
				try {
			    mSyncManager.setLockedAddress("",true);
			    try {
				Thread.sleep(1000);
			    } catch (Exception e) {
			    }			    
			    mSyncManager.disconnect();
			    handler.sendEmptyMessage(MESSAGE_UNBIND_FINISH);
			    clearBetteryNotifi();
			    Intent intent = new Intent(MainActivity.this,BindHanlangActivity.class);	    
			    startActivity(intent);
			    finish();
			    } catch (Exception e) {
			    	e.printStackTrace();
			    }
			}
		    }).start();
	    }		
	
        private Runnable takePhotoRunnable = new Runnable() {
		
		@Override
		public void run() {
		    takePhotoBt.setEnabled(true);
		      //takePhotoBt.setAlpha(255);
		}
	};

        private Runnable takeVideoRunnable = new Runnable() {
		
		@Override
		public void run() {
		    takeVideoBt.setEnabled(true);
		      //takeVideoBt.setAlpha(255);
		}
	};

	private void disableLocalData(){	
		SharedPreferences sp = getSharedPreferences(SyncApp.SHARED_FILE_NAME
									  ,MODE_PRIVATE);
		Editor editor = sp.edit();    
		editor.clear();  
		editor.commit();
		
		SharedPreferences defaultSp = PreferenceManager.getDefaultSharedPreferences(this);
		Editor defaultEditor = defaultSp.edit();
		defaultEditor.clear();
		defaultEditor.commit();
    }    
	
	private void turnApOff() {
		PhotosSyncRunnable photosSyncRunnable = PhotosSyncRunnable.getInstance();
		VideoSyncRunnable videoSyncRunnable = VideoSyncRunnable.getInstance();
		WifiManager wifimanager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		if(!photosSyncRunnable.isRunning()&&!videoSyncRunnable.isRunning()&&
				WifiUtils.getWifiAPState(wifimanager) == 13) {
			showTurnApOffDialog();
		}
		else {
			quit();
		}
	}
	
	private void showTurnApOffDialog() {
		
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(R.string.turn_wifi_ap_off);
		builder.setMessage(R.string.wifi_ap_hint_off);
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
						WifiManager wifimanager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
						WifiUtils.setWifiApEnabled(false, wifimanager);
						return null;
					}
				}.execute();
				
				dialog.cancel();
				quit();
			}
		});
		
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
				quit();
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				quit();
			}
		});
		dialog.show();
	}
	
	private void quit() {
		super.onBackPressed();
	}
	
	private void showUpdateConfirmDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.software_updates);
		builder.setMessage(R.string.updates_note);
		builder.setNegativeButton(R.string.update_later, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		
		builder.setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				Intent intent =new Intent(MainActivity.this,WifiListActivity.class);
				intent.putExtra("wifi_type",WifiListActivity.TYPE_UPDATE);
				startActivity(intent);
			}
		});
		
		builder.create().show();
	}
	
	private void clearBetteryNotifi(){
		// 删除通知   
		NotificationManager notificationManager = (NotificationManager) this 
			.getSystemService(NOTIFICATION_SERVICE);   
		notificationManager.cancel(100);  
	}

        private void startSilentLive(){
	        Packet pk = mHanLangCmdChannel.createPacket();
		pk.putInt("type", SettingFragment.SET_LIVE_AUDIO);
		pk.putBoolean("audio", false);
		mHanLangCmdChannel.sendPacket(pk);
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
		Editor editor = preferences.edit();
		editor.putBoolean("live_audio", false);
		editor.commit();
		Intent intent = new Intent(MainActivity.this, LiveDisplayActivity.class);
		startActivity(intent);
	}
    
        	public class SetWifiAPTask extends AsyncTask<Boolean, Void, Void> {
    	
		private boolean mMode;
		private boolean mFinish;
		
		public SetWifiAPTask(boolean mode, boolean finish) {
		    mMode = mode;
		    mFinish = finish;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Log.i(TAG,"-----SetWifiAPTask onPreExecute------");
			mConnectProgressDialog.setMessage(getResources().getText(R.string.turning_wifi_ap_on));
			mConnectProgressDialog.show();
		}

		@Override
		protected void onPostExecute(Void aVoid) {
			super.onPostExecute(aVoid);
			Log.i(TAG,"-----SetWifiAPTask onPostExecute------");
			//updateStatusDisplay();
//			if (mFinish) mContext.finish();
		}

		@Override
		protected Void doInBackground(Boolean... off) {
			Log.i(TAG, "doInBackground");
			try {
				if(off[0])
					WifiUtils.toggleWifi(mContext, mWifiManager);
				WifiUtils.turnWifiApOn(mContext, mWifiManager, WifiCipherType.WIFICIPHER_NOPASS);
			} catch(Exception e) {
				e.printStackTrace();
			}
		    return null;
		}
    }

    private BroadcastReceiver mApStateBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(intent.getAction())) {
				int cstate = intent.getIntExtra("wifi_state", -1);
				Log.e(TAG, "WIFI_AP_STATE_CHANGED_ACTION:" + cstate);
				if(cstate == WifiUtils.WIFI_AP_STATE_ENABLED
						) {
					
					BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
					if(!adapter.isEnabled()) {
						adapter.enable();
					}
					WifiManagerApi mWifiManagerApi = new WifiManagerApi(mContext);
					WifiConfiguration mWifiConfiguration = mWifiManagerApi.getWifiApConfiguration();
					Log.e(TAG, "ssid:" + mWifiConfiguration.SSID + "password:" + mWifiConfiguration.preSharedKey);
					setProgressDialog();
					sendApInfoToGlass();
					mRegistApStateBroadcastReceiver = false;
					mContext.unregisterReceiver(mApStateBroadcastReceiver);
				}
			}
		}
		
	};

    public void sendApInfoToGlass() {
		
		if(mHanLangCmdChannel.isConnected()) {			
			Packet packet = mHanLangCmdChannel.createPacket();
			packet.putInt("type", HanLangCmdChannel.CONNET_WIFI_MSG);
			
			String ssid = WifiUtils.getValidSsid(mContext);
			String pw = WifiUtils.getValidPassword(mContext);
			String security = WifiUtils.getValidSecurity(mContext);
			
			packet.putString("ssid", ssid);
			packet.putString("pw", pw);
			packet.putString("security", security);
			mHanLangCmdChannel.sendPacket(packet);
			Log.i(TAG,"---sendApInfoToGlass ssid: "+ssid+" pw: "+pw+" security: "+security);
			handler.sendEmptyMessageDelayed(MSG_RESEDN_CONNECT_WIFI, 5000);
		}
		else {
			if(mConnectProgressDialog.isShowing())
				mConnectProgressDialog.dismiss();
			Toast.makeText(mContext, R.string.bluetooth_error, Toast.LENGTH_LONG).show();
		}
    }

        private void setProgressDialog(){
	    if(mHanLangCmdChannel.isConnected()) {		
		mConnectProgressDialog.setMessage(getResources().getText(R.string.wait_device_connect));
		if(!mConnectProgressDialog.isShowing())
		    mConnectProgressDialog.show();
	    }
	}
	private void getWifiConnectState() {
	      //phone wifi ap opened
	    if(WifiUtils.getWifiAPState(mWifiManager) == WifiUtils.WIFI_AP_STATE_ENABLED && mHanLangCmdChannel.isConnected()){
		Log.i(TAG,"getWifiConnectState ");
		    Packet pk = mHanLangCmdChannel.createPacket();
		    pk.putInt("type", 28);
		    mHanLangCmdChannel.sendPacket(pk);
	    }else {
		mSyncHotspotBt.setTextColor(mContext.getResources().getColor(R.color.black));
		mSyncHotspotBt.setText(mContext.getResources().getString(R.string.sync_phone_wifi_hotspot));
	    }
	}

	private void openApAndSendApInfoToGlass() {
		if(WifiUtils.getWifiAPState(mWifiManager) == WifiUtils.WIFI_AP_STATE_ENABLED){
			setProgressDialog();
			sendApInfoToGlass();
		}else {
			IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
			mContext.registerReceiver(mApStateBroadcastReceiver,filter);
			mRegistApStateBroadcastReceiver = true;
			mWifiATask = new SetWifiAPTask(true, false);
			mWifiATask.execute(false);
		}
	}
}
